package email

import (
	"common"
	"common/json_response"
	"common/zapx"
	context2 "context"
	"gateway/internal/pb"
	"gateway/internal/types/v1/email"
	"github.com/gin-gonic/gin"
	"go.uber.org/zap"
	"google.golang.org/grpc"
	"google.golang.org/grpc/credentials/insecure"
	"time"
)
import _ "github.com/mbobakov/grpc-consul-resolver"

// SendSmsEmail 发送验证邮件
func SendSmsEmail(context *gin.Context) {
	resp := json_response.NewJsonHttpResponse(context)
	var request email.SendSmsRequest
	if err := context.ShouldBindJSON(&request); err != nil {
		resp.SetMsg(err.Error()).SetCode(json_response.CODE_ERROR).Send()
		return
	}
	conn, err := grpc.Dial(
		common.ConsulSerUrl("email"),
		grpc.WithTransportCredentials(insecure.NewCredentials()),
	)
	if err != nil {
		zapx.Logger.Error("链接邮件发送服务失败", zap.Error(err))
		resp.SetCode(json_response.CODE_ERROR).SetMsg("系统错误").Send()
		return
	}
	defer conn.Close()
	client := pb.NewEmailClient(conn)
	timeoutCtx, cancel := context2.WithTimeout(context2.Background(), time.Second*3)
	defer cancel()
	_, err = client.SendVerifyEmail(timeoutCtx, &pb.SendVerifyEmailRequest{
		Email: request.Email,
		Event: request.Event,
	})
	if err != nil {
		zapx.Logger.Error("调用邮件发行服务失败", zap.Error(err))
		resp.SetCode(json_response.CODE_ERROR).SetMsg("系统错误").Send()
		return
	}
	resp.SetMsg("发送成功").Send()
}
